// 记录本地nedb操作记录，保存到单独数据库，用户点击同步时，与云服务器的数据进行同步
import {
	ref,
	reactive
} from 'vue'
import nedb from "@/nedb/db.js";
const asyncDb = nedb.getInstance('async')
const asyncList = reactive([])
let AsyncLength = ref(0)
// 监听数据更改uni.$on的全局接听监听
uni.$on('AsyncLength', (data) => {
	// console.log('监听到事件来自 AsyncLength ，携带参数为：' + data);
	AsyncLength.value = data
})
const getAsyncList = async (condition = {}) => {
	const res = await asyncDb.find(condition)
	if (res.code != 1) {
		asyncList.value = res.data
		AsyncLength.value = res.data.length
		console.log(AsyncLength.value)
	}
	return res
}
const getAsyncOne = async (_id, title, docid) => {
	let dataObj = reactive({})
	if (_id != '') {
		dataObj._id = _id
	}
	if (docid != '') {
		dataObj.docid = docid
	}
	if (title != '') {
		dataObj.title = title
	}
	const res = await asyncDb.findOne(dataObj)
	return res
}
// 添加本地操作记录
let addAsync = async (type, data, docid) => {
	// 如果是更新操作，就只保留最后一条
	if (type == 'update' || type == 'updatetodo') {
		console.log("addAsync执行更新记录222：")
		const findRes = await getAsyncList({
			docid
		})
		if (findRes.code == 0) {
			findRes.data.forEach(async (item) => {
				if (item.type == "update" || item.type == "updatetodo") {
					console.log(item)
					await delAsync(item._id)
				}
			})
		}
	}
	// 如果是删除操作就把关于该条的记录全删除
	if (type == 'del' || type == 'deltodo') {
		const findRes = await getAsyncList({
			docid
		})
		console.log("addAsync执行删除时的记录：", findRes)
		//执行删除操作的记录时，如果找到了该删除操作的新建记录和更新记录 那么
		// 1.把 新建记录和编辑记录同时删掉，2最后，也不记录本次删除操作
		// findRes._id是找到的新建记录ID，我们接下来就执行删除和停止
		if (findRes.code == 0) {
			for (let i = 0; i < findRes.data.length; i++) {
				console.log('删除记录')
				await delAsync(findRes.data[i]._id)
			}
			return
		}
	}
	const dataObj = {
		type,
		data,
		docid,
	}
	const res = await asyncDb.insert(dataObj)
	uni.showToast({
		title: "async插入同步记录成功",
		icon: "none"
	})
	await getAsyncList()
	return res
}
let delAsync = async (_id) => {
	const dataObj = reactive({
		_id
	})
	const res = await asyncDb.del(dataObj)
	const AsyncList = await getAsyncList()
	// 删除分组后，利用uni.$emit通知更改数据
	AsyncList.code == 0 ? uni.$emit('AsyncLength', AsyncList.data.length) : uni.$emit('AsyncLength', 0)
	return res
}
let updateAsync = async (_id, title) => {
	const dataObj = reactive({
		_id,
	})
	const res = await asyncDb.update(dataObj, {
		title
	})
	uni.showToast({
		title: "修改成功",
		icon: "none"
	})
	await getAsyncList()
	return res
}
export {
	asyncList,
	getAsyncList,
	getAsyncOne,
	addAsync,
	delAsync,
	updateAsync,
	AsyncLength
}
